package com.glkj.vipsystem.modules.app.interceptor;


import com.glkj.vipsystem.common.exception.BizException;
import com.glkj.vipsystem.entity.ao.MemberAO;
import com.glkj.vipsystem.modules.app.annotation.LoginIgnore;
import com.glkj.vipsystem.modules.app.utils.JwtUtils;
import com.glkj.vipsystem.service.IMemberService;
import io.jsonwebtoken.Claims;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 权限(Token)验证
 *
 * @author LiMuchan
 */
@Component
public class AuthorizationInterceptor extends HandlerInterceptorAdapter {

    @Resource
    private JwtUtils jwtUtils;
    @Resource
    private IMemberService memberService;
    public static final String USER_KEY = "member";

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        LoginIgnore annotation;
        if (handler instanceof HandlerMethod) {
            annotation = ((HandlerMethod) handler).getMethodAnnotation(LoginIgnore.class);
        } else {
            return true;
        }

        // 带有LoginIgnore 忽略验证
        if (annotation != null) {
            return true;
        }
        valid(request);


        return true;
    }

    private void valid(HttpServletRequest request) {
        String header = jwtUtils.getHeader();
//        System.out.println(header);
        //获取用户凭证
        String token = request.getHeader(header);
        if (StringUtils.isBlank(token)) {
            token = request.getParameter(header);
        }
//        System.out.println(token);
        //凭证为空
        if (StringUtils.isBlank(token)) {
            throw new BizException(header + "不能为空", -1);
        }

        Claims claims = jwtUtils.getClaimByToken(token);
        if (claims == null || jwtUtils.isTokenExpired(claims.getExpiration())) {
            throw new BizException(header + "失效，请重新登录", -1);
        }

        String key = claims.getSubject();
        // 设置openid以供后续访问
        request.setAttribute("openid", key);

        String servletPath = request.getServletPath();
        // 绑定手机时 不需要校验用户是否存在
        if (servletPath.equals("/api/bind")) {
            return;
        }

        MemberAO memberAO = memberService.selectByOpenid(key);

        if (memberAO == null) {
            throw new BizException(header + "请先绑定手机", -2);
        }
        //设置用户到request里，后续，获取用户信息
        request.setAttribute(USER_KEY, memberAO);
    }
}
